package com.cpr.core.rabbitmq.client.consumerack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author Chen Panrui
 * created at 2022/3/20 17:17
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        // 指定协议 用户名+密码+host+端口号+虚拟主机
        factory.setUri("amqp://admin:123456@106.13.89.7:5672/%2f");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("queue.consumer.ack", false, false, false, null);

        channel.basicConsume("queue.consumer.ack", false,"myConsumer", new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                // 手动确认消息
                //channel.basicAck(envelope.getDeliveryTag(), false);
                // 用于拒收 多条消息
                //channel.basicNack(envelope.getDeliveryTag(), false, true);
                // 用于拒收 1条消息
                // 参数requeue-对于不确认的消息是否重新入列，重新发送
                System.out.println("收到消息:" + new String(body));
                channel.basicReject(envelope.getDeliveryTag(), true);
            }
        });

        //channel.close();
        //connection.close();
    }
}
